package demo02;

import lombok.Data;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.function.Function;


public class Test02 {
    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {
        Map<String, Object> map = Map.of("name", "Hanser", "age", 18, "address", "China", "sex", "Male");
        Person person = somethingToObj(Person.class, map::get);
        Teacher teacher = somethingToObj(Teacher.class, map::get);
        System.out.println(person);
        System.out.println(teacher);
    }

    public static <T> T somethingToObj(Class<T> clazz, Function<String, Object> function) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
        T t = clazz.getConstructor().newInstance();
        Field[] declaredFields = t.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            declaredField.set(t, function.apply(declaredField.getName()));
        }
        return t;
    }

    @Data
    static class Person implements Serializable {
        private String name;
        private Integer age;
        private String address;
    }

    @Data
    static class Teacher {
        private String name;
        private Integer age;
        private String address;
        private String sex;
    }

}
